package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import svc.LoginSvc;

/**
 * Servlet implementation class UpdatePassword
 */
//@WebServlet("/UpdatePassword")
public class UpdatePassword extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private LoginSvc svc = new LoginSvc();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdatePassword() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		HttpSession session = request.getSession();
		String email = request.getParameter("email");
	    String oldPassword = request.getParameter("oldpass");
	    String newPassword = request.getParameter("newpass");
	    String reNewPassword = request.getParameter("renewpass");
	    String passwordUpdateMessage = "";
	    
	    boolean passwordsMatch = newPassword.equals(reNewPassword);
	    
	    if(email.length()==0 || oldPassword.length()==0 || newPassword.length()==0){
	    	passwordUpdateMessage = "All fields are mandatory.";
	    }else if(!passwordsMatch){
	    	passwordUpdateMessage = "Passwords do not match!";
	    }else{
	    	int userId = svc.isUidPwdValid(email, oldPassword);
	    	if(userId>0){
	    		passwordUpdateMessage = "Email or password does not match our database";
	    	}else{
	    		boolean isPasswordUpdated = svc.updatePassword(email, newPassword);
	    		
	    		if(isPasswordUpdated){
	    			passwordUpdateMessage = "Your password has been updated, please login to continue.";
	    		}else{
	    			passwordUpdateMessage = "Sorry, your request is not complete due to an unexpected error, kindly try again later.";
	    		}
	    	}
	    }
	    
	    session.setAttribute("passwordUpdateMessage", passwordUpdateMessage);
	    response.sendRedirect("../jsp/login.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

}
